package com.jm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jm.constants.SystemConstants;
import com.jm.domain.ResponseResult;
import com.jm.domain.dto.AddArticleDto;
import com.jm.domain.entity.Article;
import com.jm.domain.entity.ArticleTag;
import com.jm.domain.entity.Category;
import com.jm.domain.vo.*;
import com.jm.enums.AppHttpCodeEnum;
import com.jm.exception.SystemException;
import com.jm.mapper.ArticleMapper;
import com.jm.service.ArticleService;
import com.jm.service.ArticleTagService;
import com.jm.service.CategoryService;
import com.jm.utils.BeanCopyUtils;
import com.jm.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ArticleTagService articleTagService;

    @Override
    public ResponseResult hotArticleList() {
        //查询热门文章，封装成ResponseResult对象返回
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //根据浏览量降序排序
        queryWrapper.orderByDesc(Article::getViewCount);
        //最多只查询10条
        Page<Article> page = new Page<>(1, SystemConstants.HOT_ARTICLE_DISPLAYED_COUNT);
        page(page, queryWrapper);

        List<Article> records = page.getRecords();
//        List<HotArticleVo> hotArticleVos = new ArrayList<>();
//        for(Article article:records){
//            HotArticleVo vo=new HotArticleVo();
//            BeanUtils.copyProperties(article,vo);
//            hotArticleVos.add(vo);
//        }
        //bean拷贝
        List<HotArticleVo> hotArticleVos = BeanCopyUtils.copyBeanList(records, HotArticleVo.class);
        return ResponseResult.okResult(hotArticleVos);
    }

    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        //查询文章表，正式发布文章
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //状态是正常发布
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //categoryId询时要和传入的相同
        queryWrapper.eq(Objects.nonNull(categoryId) && categoryId > 0,
                Article::getCategoryId, categoryId);
        //置顶文章在前面 isTop属性 1为置顶
        queryWrapper.orderByDesc(Article::getIsTop);


        //分页查询
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);

        List<Article> articles = page.getRecords();
        //查询categoryName
        articles.stream()
                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName())
                )
                .collect(Collectors.toList());

        //封装vo
        List<ArticleListVo> articleListVos = BeanCopyUtils.copyBeanList(articles, ArticleListVo.class);
        PageVo pageVo = new PageVo(articleListVos, page.getTotal());

        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult getArticleDetail(Long id) {
        //根据文章id，查询文章具体信息
        Article article = getById(id);
        if (Objects.isNull(article)) {
            throw new SystemException(AppHttpCodeEnum.ARTICLE_NOT_EXIST);
        }
        //4.查询页面时，从redis中读取viewCount数据
        Integer viewCount = redisCache.getCacheMapValue(SystemConstants.ARTICLE_VIEW_COUNT, id.toString());
        article.setViewCount(viewCount.longValue());
        //封装vo
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);
        //查询分类名称
        Long categoryId = articleDetailVo.getCategoryId();
        Category category = categoryService.getById(categoryId);
        if (category != null) {
            articleDetailVo.setCategoryName(category.getName());
        }

        return ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        //优化：
        /**
         * 1.项目启动，自动加载mysql{id:viewCount}数据到redis √
         * 2.流量增加，在redis中增加
         * 3.每隔一段时间，同步redis数据到mysql
         * 4.查询页面时，从redis中读取viewCount数据
         */
        //2.流量增加，在redis中增加
        redisCache.incrementCacheMapValue(SystemConstants.ARTICLE_VIEW_COUNT, id.toString(), 1L);
        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public ResponseResult add(AddArticleDto articleDto) {
        //转换为实体类，保存到数据库
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        save(article);
        //获取文章对应的标签，存到文章标签关系表、标签表中
        List<ArticleTag> articleTagList = articleDto.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());
        articleTagService.saveBatch(articleTagList);

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult listArticlePage(Integer pageNum, Integer pageSize, String title,String summary ) {
        //查询条件
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!(title==null||title==""),Article::getTitle, title);
        queryWrapper.eq(!(summary==null||summary==""),Article::getSummary, summary);
        //分页查询
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);
        //封装vo
        List<Article> records = page.getRecords();
        List<ArticleVo> articleVos = BeanCopyUtils.copyBeanList(records, ArticleVo.class);
        PageVo pageVo = new PageVo(articleVos,page.getTotal());
        return ResponseResult.okResult(pageVo);
    }


    @Override
    public ResponseResult getArticleById(Long id) {
        LambdaQueryWrapper<ArticleTag> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleTag::getArticleId,id);
        List<String> tags = articleTagService.list(queryWrapper).stream()
                .map(articleTag -> articleTag.getTagId().toString())
                .collect(Collectors.toList());
        Article article = getById(id);
        ArticleVo articleVo = BeanCopyUtils.copyBean(article, ArticleVo.class);
        articleVo.setTags(tags);
        return ResponseResult.okResult(articleVo);
    }

    @Override
    @Transactional
    public ResponseResult updateArticle(Article article) {
        //更新article表
        updateById(article);
        //查询新的关系
        List<String> tags = article.getTags();
        //删除文章标签关系
        LambdaQueryWrapper<ArticleTag> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleTag::getArticleId,article.getId());
        articleTagService.remove(queryWrapper);
        //添加新的文章标签关系
        List<ArticleTag> articleTagList = tags.stream()
                .map(tagId -> new ArticleTag(article.getId(), Long.valueOf(tagId)))
                .collect(Collectors.toList());
        articleTagService.saveBatch(articleTagList);
        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public ResponseResult deleteArticle(Long id) {
        //删除文章标签关系
        LambdaQueryWrapper<ArticleTag> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleTag::getArticleId,id);
        articleTagService.remove(queryWrapper);
        //从article表删除id的数据
        removeById(id);
        return ResponseResult.okResult();
    }
}
